const express = require('express');
const { port } = require('./config')
const app = express()
const fs = require('fs');
// const https = require('https');
const path = require('path');
//定时任务刷新数据库
const schedule = require('node-schedule');
// 中间件
const Cors = require('cors')
const morgan = require('morgan')
const { json, urlencoded } = require('body-parser')
const { Token } = require('./middleware/interceptor')
const format = require('./middleware/format')


// 路由
//管理端
const AdminRouter = require('./routes/admin')
const WxRouter = require('./routes/wx')
const AllRouter = require('./routes/all')

// 日志
// const log4js = require('log4js')
require('./util/common')

// 跨域处理
app.use(Cors())
// 请求输出到控制台
app.use(morgan('dev'))
// 解析request body
app.use(json());
app.use(urlencoded({ extended: false }));
// 格式化ip、分页参数
app.use(format)

// * 证书
// const options = {
//     key: fs.readFileSync(path.join(__dirname, './ssl/star_wust_edu_cn.key')),
//     cert: fs.readFileSync(path.join(__dirname, './ssl/star_wust_edu_cn.pem')),
// };

// app.set('porthttps', 8182);

// https.createServer(options, app).listen(app.get('porthttps'), () => {
//     console.log('8182端口运行');
// });


//日志配置
// log4js.configure('./config/log4js.json');
// 请求输出到日志
// app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));

app.use(Token())


app.use('/api/test', (req, res) => {
    res.send('测试成功')
})

// 管理端路由
app.use('/api', AdminRouter)
//微信路由
app.use('/api', WxRouter)
// 全局路由
app.use('/api', AllRouter)


// 错误页
app.use('/', (req, res) => {
    res.status(404).json({
        msg: '资源不存在',
        path: req.path
    })
})

// //定时任务
// const job = schedule.scheduleJob('0 0 * * *', () => {
//     refreshDateView();
//     console.log('定时任务执行成功')
// });


//监听端口
app.listen(port, () => {
    console.log(`服务器启动成功,端口${port},环境${process.env.NODE_ENV || 'development'}！`)
})
